/*jslint vars: true, forin: true, sloppy: true */
/*global probe, angular */
probe.controller("PositionEdit", function ($scope, $element, ocAPI, ocDialog, privilege) {
	var DI = ocDialog.queryDI($element),
		teamId = DI.share.teamId,
		positionId = DI.share.positionId,
		teamRoleList = DI.share.rolesOfTeam;

	$scope.rolesOfTeam = teamRoleList;
	$scope.privilege = privilege;

	$scope.roleChecked = {};
	$scope.privilegeChecked = {};

	$scope.position = {
		id: undefined,
		name: '',
		comment: '',
		roles: [],
		privileges: []
	};

	function checkedListToObject(list) {
		var o = {};
		angular.forEach(list, function (id) {
			o[id] = true;
		}, o);
		return o;
	}
	function checkedObjectToList(obj) {
		var l = [];
		angular.forEach(obj, function (isChecked, id) {
			if (isChecked === true) {
				this.push(parseInt(id, 0));
			}
		}, l);
		return l;
	}
	function getPosition() {
		ocAPI.use('getPosition').by(positionId, teamId).then(function (data) {
			DI.$$scope.title = data.position.name + ' - 职位编辑';

			$scope.position = data.position;
			$scope.privilegeChecked = checkedListToObject(data.position.privileges);

			ocAPI.use('listRoleOfPosition')
				.by(positionId, teamId).then(function (data) {
					$scope.position.roles = data.roles;
					$scope.roleChecked = checkedListToObject(data.roles);
				});
		});
	}

	$scope.savePosition = function () {
		var p = $scope.position;
		p.roles = checkedObjectToList($scope.roleChecked);
		p.privileges = checkedObjectToList($scope.privilegeChecked);

		function saveCallback() {
			DI.closeDialog();
			DI.share.refreshRoleListOfTeam();
		}

		if (angular.isDefined(positionId)) {
			ocAPI.use('updatePosition').by(positionId, p, teamId)
				.then(saveCallback);
		} else {
			ocAPI.use('createPosition').by(p, teamId)
				.then(saveCallback);
		}
	};


	// init.
	if (angular.isDefined(positionId)) {
		getPosition();
	}
});
